package com.cl.blog.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cl.blog.util.SpringUtils;
import com.cl.blog.web.WebsocketEndpoint;
import com.cl.blog.web.WebsocketEndpoint1;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @Author 付
 * @Date 2024-03-27 13:28
 * @Version 1.0
 * @description
 * @since 1.0
 */
@Component
public class RedisMessageListener2 implements MessageListener {
	//用户的session
	private Session session;

	//用户的ID
	private String userId;


	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}


	@Override
	public void onMessage(Message message, byte[] bytes) {

		WebsocketEndpoint websocketEndpoint = (WebsocketEndpoint) SpringUtils.getBean("websocketEndpoint");
		WebsocketEndpoint1 websocketEndpoint1 = (WebsocketEndpoint1) SpringUtils.getBean("websocketEndpoint1");
		// 获主题名称
		String channel = new String(message.getChannel());
		String msg = new String(message.getBody());     //消息体
		JSONObject entries = JSONUtil.parseObj(msg);

		System.out.println("获取的频道--"+channel+"--获取的信息——--"+entries+"----userId---"+userId);
		if (message != null) {
			synchronized (this) {
				System.out.println("redis中订阅消息");
				if (channel.equals("test")) {
					//根据自身的业务需要编写
					//下面是通过用户id，调用socket给对应的用户发送信息
//					websocketEndpoint.sendMessageToUser(message.toString(), userId);
					try {
						websocketEndpoint.sendMessageToUser(message.toString(), String.valueOf(2));
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				} else if (channel.equals("limit")) {
					//根据自身的业务需要编写
					Object receiver = entries.get("receiver");
					//下面是通过用户id，调用socket给对应的用户发送信息
					try {
						websocketEndpoint.sendMessageToUser(message.toString(), String.valueOf(receiver));
//						websocketEndpoint1.sendMessage(message.toString());
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			}
		}
	}
}